package com.ax.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.ax.entity.Result;
import com.ax.mapper.TbBookcaseMapper;
import com.ax.pojo.TbBook;
import com.ax.pojo.TbBookcase;
import com.ax.pojo.TbBookcaseExample;
import com.ax.service.BookCaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class BookCaseServiceImpl implements BookCaseService {

    @Autowired
    private TbBookcaseMapper bookcaseMapper;

    @Override
    /*添加书籍到书架中*/
    public Result addBookToCase(String lid, String bookId) {

        Result result;
        // 判断书籍的接收完整性
        if (lid == null
                || StringUtils.isEmpty(bookId)) {
            result = new Result(false, "信息错误");
            return result;
        }
        TbBookcase bookcase = new TbBookcase();
        bookcase.setId(UUID.randomUUID().toString());
        bookcase.setBid(lid);
        bookcase.setBookId(bookId);
        bookcase.setCreateTime(new Date());
        bookcase.setUpdateTime(new Date());
        bookcaseMapper.insert(bookcase);
        result = new Result(true, "添加成功", bookcase);
        return result;
    }

    @Override
    public List<TbBook> findCaseBook(String lid) {

        return this.stateOfBooks(lid, 1);
    }

    @Override
    public List<TbBook> findLendingBook(String lid) {

        return this.stateOfBooks(lid, 2);
    }

    @Override
    public List<TbBook> findLendBook(String lid) {

        return this.stateOfBooks(lid, 3);
    }

    @Override
    public List<TbBook> findReturnBook(String lid) {

        return this.stateOfBooks(lid, 4);
    }

    @Override
    public void deleteBookToCase(String bookId) {

        // 删除书
        bookcaseMapper.deleteBook(bookId);
        // 删除书架中的书

        TbBookcaseExample bookcaseExample = new TbBookcaseExample();
        bookcaseExample.createCriteria().andBookIdEqualTo(bookId);
        bookcaseMapper.deleteByExample(bookcaseExample);
    }

    public List<TbBook> stateOfBooks(String bid, Integer state) {
        // 查询属于bid的书包
        TbBookcaseExample bookcaseExample = new TbBookcaseExample();
        bookcaseExample.createCriteria().andBidEqualTo(bid);
        List<TbBookcase> tbBookcases = bookcaseMapper.selectByExample(bookcaseExample);
        List<TbBook> books = new ArrayList<TbBook>();
        for (TbBookcase bookcase : tbBookcases) {
            TbBook tbBook = bookcaseMapper.selectBooKById(bookcase.getBookId());
            if (tbBook.getStatus() == state) {
                books.add(tbBook);
            }
        }
        return books;
    }
}
